package com.eboss2.sbs.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.text.format.DateUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.ActivityGetEms;
import com.eboss2.sbs.activity.ActivityOrderDetail;
import com.eboss2.sbs.adapter.OrderManagerAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.interfaces.EditPriceCallbackListener;
import com.eboss2.sbs.interfaces.EmsCallbackListener;
import com.eboss2.sbs.interfaces.OrderManagerCallBackListener;
import com.eboss2.sbs.model.MessageEvent;
import com.eboss2.sbs.model.OrderManagerInfo;
import com.eboss2.sbs.myapplication.MyApplication;
import com.eboss2.sbs.weight.DialogUtils;
import com.eboss2.sbs.weight.MyCustomDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.views.MyDialog;
import com.tool.utils.utils.LogUtils;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.view.MyListView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class FragmentOrderManagerAll extends AbstractFragment{
    private static final String TAG = "FragmentOrderManagerAll";

    private PullToRefreshScrollView mPullRefreshScrollView;
    private List<OrderManagerInfo> orderManagerInfos = new ArrayList<>();
    private OrderManagerAdapter adapter;
    private MyListView myListView;
    private int page = 1;
    private boolean showProgress = false;
    private static Context sContext;
    private String emsName;



    @Override
    protected void initView() {

        showProgress = false;
        sContext = mContext;

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }


        myListView = findViewById(R.id.listview);
        adapter = new OrderManagerAdapter(mContext, orderManagerInfos, new OrderManagerCallBackListener() {
            @Override
            public void addBack(long id, String data, ImageView img_qi, MyCustomDialog dialog) {
                setAddBack(id, data, img_qi, dialog);
            }

            @Override
            public void setFh(long id, String emsName, String emsShortName, String expressNo, MyCustomDialog dialog) {
//                showEmsNo(id);
                startActivity(new Intent(mContext, ActivityGetEms.class).putExtra("id", id).putExtra("type", "all"));
            }

            @Override
            public void setZt(final long id) {
                MyDialog.Builder builder = new MyDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setMessage("确定要自送吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
                        doMechantSend(id, dialog);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }

            @Override
            public void setCancalOrder(final long id) {

                MyDialog.Builder builder = new MyDialog.Builder(mContext);
                builder.setTitle("提示");
                builder.setMessage("确定取消订单吗？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
                        doCancalOrder(id, dialog);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int arg1) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();

            }

            @Override
            public void EditPrice(long id, Integer goodAmount, Integer freightCharge) {
                showEditPrice(id, goodAmount, freightCharge);
            }

            @Override
            public void RefundSure(long id, DialogInterface dialog, String amt, String content) {
                doRefundSure(id, amt+"", content, dialog, 1);
            }

            @Override
            public void RefundRefused(long id, MyCustomDialog dialog, String reason) {
                doRefundSure(id, "", reason, dialog, 2);
            }
        });
        myListView.setAdapter(adapter);
        myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                ToastUtils.CustomShow(mContext, ""+i);
                startActivity(new Intent(mContext, ActivityOrderDetail.class).putExtra("type", "all").putExtra("status", orderManagerInfos.get(i).getStatus()).putExtra("orderId", orderManagerInfos.get(i).getId()));
            }
        });


        mPullRefreshScrollView = findViewById(R.id.pull_refresh_scrollview);
        // 下拉刷新、上拉加载更多
        mPullRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        // TODO:必须先设置Mode后再设置刷新文本
        ILoadingLayout startLabels = mPullRefreshScrollView.getLoadingLayoutProxy(true, false);
        startLabels.setPullLabel("下拉刷新...");// 刚下拉时，显示的提示
        startLabels.setRefreshingLabel("正在载入...");// 刷新时
        startLabels.setReleaseLabel("释放立即刷新...");// 下来达到一定距离时，显示的提示
        // TODO:必须先设置Mode后再设置刷新文本
        ILoadingLayout endLabels = mPullRefreshScrollView.getLoadingLayoutProxy(false, true);
        endLabels.setPullLabel("上拉加载更多...");// 刚下拉时，显示的提示
        endLabels.setRefreshingLabel("正在载入...");// 刷新时
        endLabels.setReleaseLabel("释放立即加载...");// 下来达到一定距离时，显示的提示
        mPullRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                // 下拉刷新
                String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy(true, false).setLastUpdatedLabel("更新于：" + label);
                reloadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                // 上拉加载更多
                String label = DateUtils.formatDateTime(mContext, System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy(false, true).setLastUpdatedLabel("更新于：" + label);


                if (orderManagerInfos.size() == 0) {
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            showErrorMsg("没有更多了");
                            mPullRefreshScrollView.onRefreshComplete();
                        }
                    }, 1000);
                }else{
                    page++;
                    loadData();
                }


            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        if ("all".equals(messageEvent.getMessage())) {
            reloadData();
        }
    }




    private void showEditPrice(final long id, Integer goodAmount, Integer freightCharge) {
        DialogUtils.showEditPriceDialog(mContext, goodAmount, freightCharge,  new EditPriceCallbackListener() {
            @Override
            public void getData(String goodAmt, String emsAmt, String realAmt, MyCustomDialog dialog) {
                loadEditPrice(id, goodAmt, emsAmt, dialog);
            }
        });
    }

    private void loadEditPrice(Long id, String goodAmount, String emsAmt, final MyCustomDialog dialog) {
        showProgress("加载中...");
        String url = Config.SBS_CLOSE_ORDER;
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("goodAmount", StringUtils.changeY2F(goodAmount));
        params.put("freightCharge", StringUtils.changeY2F(emsAmt));

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }


    private void doRefundSure(long id, String amt, String reason, final DialogInterface dialog, int type) {


        showProgress("加载中...");
        String url = Config.SBS_REFUND_ORDER;
        RequestParams params = new RequestParams();
        params.put("id", id);

        if (type == 1) {
            params.put("status", 9);
            params.put("userRefund", 3);
            params.put("refundAmount", amt);
            params.put("refuseReason", reason);
        }else if (type == 2){
            params.put("status", 5);
            params.put("userRefund", 2);
            params.put("refuseReason", reason);
        }


        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });

    }



    private void doMechantSend(long id, final DialogInterface dialog) {


        showProgress("加载中...");
        String url = Config.SBS_CLOSE_ORDER;
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("status", 6);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });

    }


    private void doCancalOrder(long id, final DialogInterface dialog) {


        showProgress("加载中...");
        String url = Config.SBS_CLOSE_ORDER;
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("status", 8);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });

    }


    private Handler handler = new Handler();

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            loadEmsShortName();
        }
    };

    private void loadEmsShortName() {

        if (StringUtils.isBlank(emsName)){
            return;
        }

        showProgress("加载中...");
        String url = Config.SBS_GET_EMS_SHORT_NAME;
        RequestParams params = new RequestParams();
        params.put("expressName", emsName);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }


    private void showEmsNo(long id) {
        DialogUtils.showSendGoodsDialog(mContext, new EmsCallbackListener(){

            @Override
            public void getData(String emsNo, String emsName, MyCustomDialog dialog) {

            }

            @Override
            public void getScanData(EditText et_ems_no) {
//                emsNo = et_ems_no;
                startActivityForResult(new Intent(mContext, CaptureActivity.class), 1);
            }

            @Override
            public void getEmsShortname(String trim) {

                if(delayRun!=null){
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(delayRun);
//                    return;
                }
                emsName = trim;

                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler.postDelayed(delayRun, 1000);
            }
        });

    }


    private void setAddBack(long id, String data, final ImageView img_qi, final MyCustomDialog dialog){
        showProgress("加载中...");

        String url = Config.SBS_ADD_REMAKE;
        RequestParams params = new RequestParams();
        params.put("id", id);
        params.put("remark", data);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {


                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    //保存备注，成功更改旗子
//                    img_qi.setImageResource(R.mipmap.icon_qi2);
//                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                    reloadData();

                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }






    protected void lazyLoad() {
        LogUtils.e(TAG1+TAG, "lazyLoad()");
        reloadData();
    }

    @Override
    protected int setContentView() {
        return R.layout.activity_order_manager_all;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.e(TAG1+TAG, "onResume");
//        reloadData();
    }


    /**
     * 重新加载数据
     */
    private void reloadData() {
        page = 1;
        orderManagerInfos.clear();
        loadData();
    }


    private void loadData() {


        if (showProgress){
            return;
        }

        showProgress = true;

        String url = Config.SBS_MALL_ORDER_LIST;
        RequestParams params = new RequestParams();
        params.put("shopId", MyApplication.getmInstance().getLoginMEntity().getShopid()+"");
        params.put("status", "");
        params.put("pageNo",page+"");
        params.put("pageSize","15");
        showProgress("加载中...");

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @Override
            public void success(String response) {
                showProgress = false;
                disShowProgress();
                try {

                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        // 刷新完成
                        mPullRefreshScrollView.onRefreshComplete();
                        return;
                    }
                    JSONObject obj = result.getJSONObject("data");
                    String orderList = obj.optString("orderList");
                    if (!StringUtils.isBlank(orderList)) {

                        Gson gson = new Gson();
                        // json数据转换成List
                        List<OrderManagerInfo> datas = gson.fromJson(orderList, new TypeToken<List<OrderManagerInfo>>() {
                        }.getType());


                        if (datas.size() > 0) {
                            orderManagerInfos.addAll(datas);
                            if (orderManagerInfos.size() > 0) {
                                linearLayout(R.id.id_no_data).setVisibility(View.GONE);
                                myListView.setVisibility(View.VISIBLE);
                            } else {
                                linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
                                myListView.setVisibility(View.GONE);
                            }

                        } else {
                            if (orderManagerInfos.size() > 0) {

                                linearLayout(R.id.id_no_data).setVisibility(View.GONE);
                                myListView.setVisibility(View.VISIBLE);
                                handler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
                                        showErrorMsg("没有更多数据");
                                    }
                                }, 1000);
                            } else {
                                linearLayout(R.id.id_no_data).setVisibility(View.VISIBLE);
                                myListView.setVisibility(View.GONE);
                            }
                        }
                    }
                    // 刷新完成
                    mPullRefreshScrollView.onRefreshComplete();
                    adapter.notifyDataSetChanged();



                } catch (JSONException e) {
                    e.printStackTrace();
                    mPullRefreshScrollView.onRefreshComplete();
                }
            }

            @Override
            public void failed(Throwable error) {
                showProgress = false;
                mPullRefreshScrollView.onRefreshComplete();
                showE404();
                disShowProgress();
            }
        });
    }






}
